package com.fingard.dsp.bank.directbank.gzdsf01;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.IContract;
import com.fingard.dsp.bank.directbank.gzdsf01.util.CfbsAPI;
import com.fingard.dsp.bank.directbank.gzdsf01.util.CfbsUtils;
import com.fingard.dsp.bank.reqrespobj.contract.*;
import com.fingard.dsp.bank.reqrespobj.contract.detail.RetAtsContractDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.ConnState;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;

import java.io.File;
import java.util.Date;

public class GZDSF01Contract extends GZDSF01Base implements IContract {

    private boolean isAuthForRec = false;

    public void setAuthForRec(boolean pSetValue) {
        isAuthForRec = pSetValue;
    }

    @Override
    public RetAtsContract contract(ReqContract p_req) throws Exception {
        RetAtsContract retAts = new RetAtsContract(p_req.reqHeader);
        RetAtsContractDetail tmpRetDetail = new RetAtsContractDetail();
        tmpRetDetail.reqSeqID = p_req.contractDetail.askNumber;
        try {
            StringBuilder tmpContractBuilder = new StringBuilder();
            tmpContractBuilder.append(GZDSF01TransCode.RECSIGN);// 交易种类
            tmpContractBuilder.append("1202");// 报文类型
            tmpContractBuilder.append(String.format("%16s", p_req.contractDetail.askNumber).replace(" ", "0"));// 交易序号
            tmpContractBuilder.append(Format.Date8Format.format(new Date()));// 委托日期
            tmpContractBuilder.append("100");// 协议操作标识
            tmpContractBuilder.append(String.format("%-12s", bankFront.org));// 收费机构代码
            tmpContractBuilder.append(String.format("%-12s", ""));// 机构分支代码
            tmpContractBuilder.append(String.format("%16s", "").replace(" ", "0"));// 业务处理方流水
            tmpContractBuilder.append(String.format("%-8s", ""));// 返回码
            String businessTypes = getBankConfig().getValueAsString("businessTypes");
            if (StringHelper.isNullOrEmpty(businessTypes)) {
                businessTypes = "00600";
            }
            String outBank = this.getBankConfig().getMapAdvanceValuesExtra("outBankMapping", new String[]{"srcCode", "srcArea"}, "value", new String[]{p_req.contractDetail.payBankCode, p_req.contractDetail.payArea});
            if (StringHelper.isNullOrEmpty(outBank)) {
                outBank = this.getBankConfig().getMapAdvanceValue("outBankMapping", "srcCode", "value", p_req.contractDetail.payBankCode);
            }
            if (StringHelper.isNullOrEmpty(outBank)) {
                outBank = p_req.contractDetail.cnapsCode;
            }
            String contractNo = "";
            if (StringHelper.hasAnyChar(outBank)) {
                contractNo = "015810" + bankFront.org + businessTypes + outBank.substring(0, 3) + p_req.contractDetail.payAct;
            }
            tmpContractBuilder.append(String.format("%-60s", contractNo));// 合同（协议）号
            //tmpContractBuilder.append(String.format("%-18s", p_req.contractDetail.sourceNoteCode));// 用户编号
            String userCode = getBankConfig().getValueAsString("signUserCode");
            WriteBankLogLn2("签约申请630请求字段用户编号字段为：" + userCode);
            userCode = p_req.contractDetail.srcXElement.getSingleTextNotNull(userCode);
            if (StringHelper.isNullOrEmpty(userCode)) {
                userCode = p_req.contractDetail.sourceNoteCode;
            }
            tmpContractBuilder.append(String.format("%-18s", userCode));// 用户编号
            tmpContractBuilder.append(CfbsAPI.rightFill(p_req.contractDetail.payName, 60, " "));// 用户名称
//			tmpContractBuilder.append(String.format("%-60s", p_req.contractDetail.payName).getBytes("GBK"));// 用户名称
            tmpContractBuilder.append(String.format("%-60s", ""));// 联系人名称
            tmpContractBuilder.append(String.format("%-60s", ""));// 联系人地址
            tmpContractBuilder.append("000000");// 联系人地址邮编
            tmpContractBuilder.append(String.format("%-25s", getBankConfig().getValueAsString("orgCellPhone")));// 联系人电话
            tmpContractBuilder.append(businessTypes);// 业务种类
            //tmpContractBuilder.append(String.format("%-12s", p_req.contractDetail.cnapsCode));// 付款行行号
            tmpContractBuilder.append(String.format("%-12s", outBank));// 付款行行号
            tmpContractBuilder.append(String.format("%-32s", p_req.contractDetail.payAct));// 付款人账号
            tmpContractBuilder.append(CfbsAPI.rightFill(p_req.contractDetail.payName, 60, " "));// 付款人名称
//			tmpContractBuilder.append(String.format("%-60s", p_req.contractDetail.payName).getBytes("GBK"));// 付款人名称
            tmpContractBuilder.append(String.format("%-1s", convertCertTypeToBank(p_req.contractDetail.certType)));// 付款人证件类型
            tmpContractBuilder.append(String.format("%-18s", p_req.contractDetail.certNum));// 付款人证件号码
            tmpContractBuilder.append(String.format("%-16s", p_req.contractDetail.cellPhone));// 付款人手机号码
            tmpContractBuilder.append(String.format("%-30s", ""));// 付款人电子邮箱
            tmpContractBuilder.append(CfbsAPI.rightFill(p_req.contractDetail.memo, 60, " "));// 附言
//			tmpContractBuilder.append(String.format("%-60s", p_req.contractDetail.memo).getBytes("GBK"));// 附言
            tmpContractBuilder.append(String.format("%-64s", "C").replace(" ", "C"));// 校验码

            WriteBankLogLn("单笔签约请求报文生成摘要前明文数据:" + tmpContractBuilder.toString());

            String tmpLoginRequest = new CfbsUtils(this.getSbLog()).txnEncSample(tmpContractBuilder.toString(), getEncryptKey(), getCharset());

            String[] retSend = sendToBank(tmpLoginRequest);

            if (ConnState.FAIL.equals(retSend[0])) {
                tmpRetDetail.respCode = "0";
                tmpRetDetail.respInfo = retSend[1];
                tmpRetDetail.signState = "fail";
                tmpRetDetail.unifiedCode = "EC999";
                tmpRetDetail.authCode = contractNo;
            } else {
                if (isAuthForRec) {//是批量授权转单笔
                    tmpRetDetail.respCode = "0";
                    tmpRetDetail.respInfo = "签约请求已提交";
                } else {
                    if (isAuthForRec) {//是批量授权转单笔
                        tmpRetDetail.respCode = "0";
                        tmpRetDetail.respInfo = "签约请求已提交";
                    } else {
                        boolean isDirectContract = getBankConfig().getValueAsBool("isDirectContract");
                        WriteBankLogLn2("签约申请直接返回签约申请中，不等通知:" + isDirectContract);
                        if (isDirectContract) {
                            tmpRetDetail.respCode = "0";
                            tmpRetDetail.respInfo = "签约请求已提交";
                            tmpRetDetail.unifiedCode = "SC000";
                            tmpRetDetail.authCode = contractNo;
                            tmpRetDetail.signConfirmType = "3";
                        } else {
                            Date timeNow = new Date();
                            String tmpContractFilePath = getTempFileDirectory(timeNow) + File.separator + "Contract" + File.separator + Format.Date10Format.format(timeNow) + ".txt";
                            File file = new File(tmpContractFilePath);
                            WriteBankLogLn("本地签约结果文件路径:" + file.getAbsolutePath());
                            int index = 0;
                            while (true) {
                                ++index;

                                String sleepTimeContract = getBankConfig().getValueAsString("sleepTimeContract");
                                if (StringHelper.isNullOrEmpty(sleepTimeContract)) {
                                    sleepTimeContract = "0";
                                }
                                Thread.sleep(new Double(Double.parseDouble(sleepTimeContract) * 1000).longValue());
                                WriteBankLogLn("第" + index + "秒后遍历单笔签约结果文件是否存在:" + file.exists());
                                if (file.exists() || (index > 20)) {
                                    break;
                                }
                            }
                            if (file.exists()) {
                                String tmpStrRet = FileHelper.readToString(file, getCharset());
                                WriteBankLogLn("单笔签约收到通知响应数据:\r\n" + tmpStrRet);
                                StringBuilder tmpSbMsg = new StringBuilder();
                                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet, tmpSbMsg);
                                if (tmpBkReader != null) {
                                    while (tmpBkReader.read("/DetailRecord")) {
                                        String askNumber = tmpBkReader.readedXElement.getSingleText("ReqSeqID");
                                        if (p_req.contractDetail.askNumber.equalsIgnoreCase(askNumber)) {
                                            tmpRetDetail.respCode = tmpBkReader.readedXElement.getSingleText("RespCode");
                                            tmpRetDetail.respInfo = tmpBkReader.readedXElement.getSingleText("RespInfo");
                                            tmpRetDetail.signState = tmpBkReader.readedXElement.getSingleText("SignState");
                                            tmpRetDetail.unifiedCode = tmpBkReader.readedXElement.getSingleText("UnifiedCode");
                                            tmpRetDetail.signConfirmType = "3";
                                            tmpRetDetail.authCode = contractNo;
                                        }
                                    }
                                } else {
                                    tmpRetDetail.respCode = "-1";
                                    tmpRetDetail.respInfo = tmpSbMsg.toString();
                                }
                            } else {
                                tmpRetDetail.respCode = "-1";
                                tmpRetDetail.respInfo = "签约记录不存在!";
                            }
                        }
                    }
                }
            }
        } catch (Exception ex) {
            tmpRetDetail.respCode = "-1";
            tmpRetDetail.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }

    @Override
    public RetAtsContract upContract(ReqContract p_req) throws Exception {
        return null;
    }

    @Override
    public RetAtsContract qryContract(ReqContract p_reqQry) throws Exception {
        RetAtsContract retAts = new RetAtsContract(p_reqQry.reqHeader);
        RetAtsContractDetail tmpRetDetail = new RetAtsContractDetail();
        tmpRetDetail.reqSeqID = p_reqQry.contractDetail.askNumber;

        try {
            Date timeNow = new Date();
            String tmpContractFilePath = getTempFileDirectory(timeNow) + File.separator + "Contract" + File.separator + Format.Date10Format.format(timeNow) + ".txt";
            File file = new File(tmpContractFilePath);
            WriteBankLogLn("本地签约结果文件路径:" + file.getAbsolutePath());
            if (file.exists()) {
                String tmpStrRet = FileHelper.readToString(file, getCharset());
                WriteBankLogLn("单笔签约收到通知响应数据:\r\n" + tmpStrRet);
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet, tmpSbMsg);
                if (tmpBkReader != null) {
                    while (tmpBkReader.read("/DetailRecord")) {
                        String askNumber = tmpBkReader.readedXElement.getSingleText("ReqSeqID");
                        if (p_reqQry.contractDetail.askNumber.equalsIgnoreCase(askNumber)) {
                            tmpRetDetail.respCode = tmpBkReader.readedXElement.getSingleText("RespCode");
                            tmpRetDetail.respInfo = tmpBkReader.readedXElement.getSingleText("InfoCode");
                            tmpRetDetail.signState = tmpBkReader.readedXElement.getSingleText("SignState");
                            tmpRetDetail.unifiedCode = tmpBkReader.readedXElement.getSingleText("UnifiedCode");
                            tmpRetDetail.signConfirmType = "3";
                            tmpRetDetail.authCode = tmpBkReader.readedXElement.getSingleText("AuthCode");
                        }
                    }
                } else {
                    tmpRetDetail.respCode = "-1";
                    tmpRetDetail.respInfo = tmpSbMsg.toString();
                }
            } else {
                tmpRetDetail.respCode = "0";
                tmpRetDetail.signState = ContractState.UNSIGNED;
                tmpRetDetail.signConfirmType = "3";
                tmpRetDetail.unifiedCode = "SC0000";
            }
        } catch(Exception ex) {
            ex.printStackTrace();
            tmpRetDetail.respCode = "-1";
            tmpRetDetail.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }

    @Override
    public RetAtsQryBatContract qryBatContract(ReqQryBatContract p_reqQry) throws Exception {
        return null;
    }
}
